<template>
  <div>
    <p>
      <el-switch
        style="margin: 10px;color: #8c939d"
        v-model="switchLayout"
        active-color="#409EFF"
        inactive-color="#8c939d"
        :active-text="$t('概览显示')"
        :inactive-text="$t('普通显示')">
      </el-switch>
    </p>
    <div v-show="switchLayout" class="filter-container" style="margin-left: 10px">
      <p style="margin: 0px">
        <el-select v-model="listQuery.couponType" clearable filterable :placeholder="$t('赠送策略')">
          <el-option v-for="index in 8" :label="drawerTitleMap[index]" :value="index"></el-option>
        </el-select>
        <el-select v-model="listQuery.bearing" clearable filterable :placeholder="$t('损耗承受单位')">
          <el-option :label="$t('门店')" value="1"></el-option>
          <el-option :label="$t('总部')" value="0"></el-option>
        </el-select>
        <el-select v-model="listQuery.status" clearable filterable :placeholder="$t('状态')">
          <el-option :label="$t('已开启')" value="1"></el-option>
          <el-option :label="$t('已关闭')" value="0"></el-option>
        </el-select>
        <el-input :placeholder="$t('请输入策略名称搜索')" v-model="listQuery.name" class="input-with-select">
        </el-input>
        <el-button :type="switchLayout?'primary':'info'" @click="getList" :icon="switchLayout?'el-icon-search':''">
          {{ $t('搜索') }}
        </el-button>
        <el-dropdown trigger="click" @command="handleCommand">
          <el-button :type="switchLayout?'primary':'info'" :icon="switchLayout?'el-icon-plus':''">
            {{ $t('添加策略') }}<i :class="switchLayout?'el-icon-arrow-down el-icon--right':''"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="index in 8" :command="index" :divided="index==4&&switchLayout"
                              :icon="switchLayout?drawerIconMap[index]:''">{{ drawerTitleMap[index] }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </p>
    </div>
    <h5 v-show="switchLayout" style="margin: 0px;padding: 0px 10px 0px 10px;font-size: 18px;">
      <svg-icon icon-class="hint" style="float: left;"/>
      <el-carousel interval="10000" direction="vertical" height="20px">
        <el-carousel-item v-for="item in useHintMs" :key="item">
          <el-link :underline="false" style="top:-2px;margin-left: 5px" type="info">
            {{ item }}
          </el-link>
        </el-carousel-item>
      </el-carousel>
    </h5>
    <div v-show="switchLayout==false" class="filter-container" style="margin-left: 10px">

      <p style="margin: 0px">
        <el-select v-model="listQuery.couponType" clearable filterable :placeholder="$t('赠送策略')">
          <el-option v-for="index in 8" :label="drawerTitleMap[index]" :value="index"></el-option>
        </el-select>
        <el-select v-model="listQuery.bearing" clearable filterable :placeholder="$t('损耗承受单位')">
          <el-option :label="$t('门店')" value="1"></el-option>
          <el-option :label="$t('总部')" value="0"></el-option>
        </el-select>
        <el-select v-model="listQuery.status" clearable filterable :placeholder="$t('状态')">
          <el-option :label="$t('已开启')" value="1"></el-option>
          <el-option :label="$t('已关闭')" value="0"></el-option>
        </el-select>
        <el-input :placeholder="$t('请输入策略名称搜索')" v-model="listQuery.name" class="input-with-select">
        </el-input>
        <button class="yuanSty" @click="getList">{{ $t('搜索') }}</button>
        <el-dropdown trigger="click" @command="handleCommand">
          <button class="yuanSty">
            {{ $t('添加策略') }}
          </button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="index in 8" :command="index" :divided="index==4&&switchLayout"
                              :icon="switchLayout?drawerIconMap[index]:''">{{ drawerTitleMap[index] }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

      </p>
    </div>

    <el-row v-show="switchLayout" gutter="4"  v-loading="loading" element-loading-spinner="el-icon-loading"
            >
      <el-col :span="4" v-for="(item, index) in list" :key="item" style="width: 330px;height: 550px">

        <el-card :body-style="{ padding: '0px',margin:'3px'}"  style="margin: 10px" shadow="always">
          <img :src="item.pictureUrl" class="image">
          <p style="padding: 0px;text-align: center;">
            <i :class="drawerIconMap[item.couponType]"></i>
            {{ drawerTitleMap[item.couponType] }}
          </p>
          <div style="padding: 0px;" >
            <h5 style="margin: 5px">{{ $t('序号:') + (index + 1) }} - {{ $t('NO:') + item.id }}</h5>
            <h5>
              <i class="el-icon-s-shop"></i>{{ lossBearingMap[item.lossBearing] }}
              <span style="font-size:10px;color: #999">（{{ $t('损耗承受单位') }}）</span>
            </h5>
            <el-divider><i class="el-icon-present"></i> {{ $t('优惠概览') }}</el-divider>
            <h6 style="margin: 0px;padding: 0px;text-align: center">
              <el-popover
                placement="top"
                trigger="focus"
                :content="item.couponName">
                <span slot="reference">
                  <el-tag class="cardTag" effect="plain1" :type="item.status==1?'':'info'"
                          size="small">{{ $t('优惠券名:') + item.couponName }}</el-tag>
                </span>
              </el-popover>
              <el-popover
                placement="top"
                trigger="focus"
                :content="item.name">
                <span slot="reference">
                  <el-tag class="cardTag" effect="plain1" :type="item.status==1?'':'info'"
                          size="small">{{ $t('策略名称:') + item.name }}</el-tag>
                </span>
              </el-popover>
              <el-tag style="margin-bottom: 2px;width: 140px;text-align: center" effect="plain1" size="small"
                      :type="item.status==1?'warning':'info'">
                {{ $t('折扣类型:') + discountTypeMap[item.discountType] }}
              </el-tag>
              <el-tag style="width: 140px;text-align: center" effect="plain1" size="small"
                      :type="item.status==1?'danger':'info'">{{ $t('最低消费:$') + item.min }}
              </el-tag>
              <el-tag v-show="item.discountType==1" style="width: 140px;text-align: center" effect="plain1" :type="item.status==1?'success':'info'"
                      size="small">{{ $t('优惠金额:') + item.discount}}
              </el-tag>
              <el-tag v-show="item.discountType==2" style="width: 140px;text-align: center" effect="plain1" :type="item.status==1?'success':'info'"
                      size="small">{{ $t('折扣比例:%') + item.discountRate }}
              </el-tag>

              <el-tag style="width: 140px;text-align: center" effect="plain1" size="small"
                      :type="item.status==1?'':'info'">
                {{ $t('限领数量:') + (item.userLimit == 0 ? $t('不限') : item.userLimit) }}
              </el-tag>
            </h6>
            <h5 style="font-size:10px;color: #999;margin: 5px">
              <el-tag effect="plain1" :style="{'margin-left':'4px'}" v-for="item in item.ranges">{{ rangesMap[item] }}</el-tag>
              ({{ $t('使用范围') }})
            </h5>

            <p style="margin: 5px">
              <span v-if="item.couponType==1"
                    style="margin: 10px 0px 10px 0px;text-align: right;font-size: 10px">{{
                  $t('数量:') + item.total
                }}</span>
              <span v-else
                    style="margin: 10px 0px 10px 0px;text-align: right;font-size: 10px">{{
                  $t('数量: 无限量')
                }}</span>
              <time class="time">{{ item.addTime }}</time>
              <span style="margin-left: 5px;float: right">
                <el-switch
                  @change="handlePush(item)"
                  v-model="item.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </span>
            </p>
            <div class="bottom clearfix">
              <el-dropdown trigger="click">
                <el-button type="text" class="button">
                  {{ $t('更多操作') }}
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="1" @click.native="handleEdit(item)" icon="el-icon-edit">{{ $t('编辑') }}
                  </el-dropdown-item>
                  <el-popconfirm
                    :confirm-button-text="$t('确定')"
                    :cancel-button-text="$t('不了')"
                    @confirm="handleRemove(item)"
                    icon="el-icon-info"
                    icon-color="red"
                    title="确定删除选择的策略吗？">
                    <el-dropdown-item slot="reference" command="2" icon="el-icon-delete">{{ $t('删除') }}
                    </el-dropdown-item>
                  </el-popconfirm>
<!--                  <el-dropdown-item command="3" @click.native="handleStatistic(item)" v-show="item.couponType!=2"
                                    icon="el-icon-data-line">统计
                  </el-dropdown-item>-->
                  <el-dropdown-item command="4" @click.native="handlePeriod(item)"
                                    v-show="item.couponType==3&&item.status==1" icon="el-icon-s-promotion">发放
                  </el-dropdown-item>
                  <el-dropdown-item command="5" @click.native="handleExport(item)" v-show="item.couponType==2">
                    导出券码
                  </el-dropdown-item>
                  <el-dropdown-item command="6" @click.native="handleGrantLogs(item)"
                                    v-show="item.couponType==3&&item.status==1" icon="el-icon-tickets">记录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button @click="handleDetails(item)" style="float: right" type="text" icon="el-icon-setting"
                         class="button">详情
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-table v-show="switchLayout==false" border :data="list" style="width: 100%;">
      <el-table-column align="center" type="index" label="序号" width="150">
      </el-table-column>
      <el-table-column align="center" prop="id" label="策略ID" width="280">
      </el-table-column>
      <el-table-column align="center" prop="name" label="赠送策略" width="250">
      </el-table-column>
      <el-table-column align="center" prop="couponName" label="优惠券名称" width="220">
      </el-table-column>
      <el-table-column align="center" prop="ranges" label="使用范围" width="250">
        <template slot-scope="scope">
          <span v-for="item in scope.row.ranges">{{ rangesMap[item] }}、</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="date" label="折扣类型" width="180">
        <template slot-scope="scope">
          {{ discountTypeMap[scope.row.discountType] }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="date" label="满减金额/比例" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.discountType==1" size="small">
            {{ scope.row.discount + $t('Dollars') }}
          </span>
          <span v-else size="small">
            {{ scope.row.discountRate }}%
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="total" label="优惠券数量" width="180">
      </el-table-column>
      <el-table-column align="center" prop="status" label="状态" width="180">
        <template slot-scope="scope">
          {{ scope.row.status ? $t('已打开') : $t('已关闭') }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="date" label="商品限制范围" width="200">
      </el-table-column>
      <el-table-column align="center" prop="date" label="区域限制" width="200">
      </el-table-column>
      <el-table-column align="center" prop="date" label="损害承受单位" width="180">
        <template slot-scope="scope">
          {{ lossBearingMap[scope.row.lossBearing] }}
        </template>
      </el-table-column>
      <el-table-column align="center"
                       label="操作"
                       width="450">
        <template slot-scope="scope">
          <el-button style="line-height: 5px" @click="handleDetails(scope.row)" size="mini">详情</el-button>
          <el-button style="line-height: 5px" @click="handleEdit(scope.row)" size="mini">编辑</el-button>
          <el-button style="line-height: 5px" @click="handleDijiPush(scope.row)" size="mini">
            {{ scope.row.status ? '打开' : '关闭' }}
          </el-button>
          <el-button style="line-height: 5px" v-show="scope.row.couponType==3&&scope.row.status==1"
                     @click="handlePeriod(scope.row)" size="mini">发放优惠
          </el-button>
          <el-button style="line-height: 5px" v-show="scope.row.couponType!=2" @click="handleStatistic(scope.row)"
                     size="mini">统计
          </el-button>
          <el-button style="line-height: 5px" v-show="scope.row.couponType==2" @click="handleExport(scope.row)"
                     size="mini">导出优惠券码
          </el-button>
          <el-popconfirm
            :confirm-button-text="$t('确定')"
            :cancel-button-text="$t('不了')"
            @confirm="handleRemove(scope.row)"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除选择的策略吗？">
            <el-button style="line-height: 5px" slot="reference" size="mini">删除</el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>


    <pagination v-show="total >= 10" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>

    <el-empty :description="$t('还没有策略...')" :image-size="350" v-show="total===0" ></el-empty>

    <el-tooltip placement="top" :content="$t('Back_to_top')">
      <back-to-top :visibility-height="100"/>
    </el-tooltip>
    <el-drawer
      size="40%"
      direction="ltr"
      :visible.sync="drawer"
      :before-close="handleClose"
      :with-header="false">
      <h3 style="text-align: center">{{ drawerTitleMap[drawerTitle] }}</h3>
      <el-form :disabled="strategyForm.status" :model="strategyForm" :rules="strategyRules" ref="strategyForm"
               label-width="150px" class="strategyForm">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input type="textarea"  :autosize="{ minRows: 1}" maxlength="255" show-word-limit class="inputSty"  v-model="strategyForm.name"
                    :placeholder="$t('请输入策略名称')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('选择优惠券')" prop="couponId">
          <el-select class="inputSty" clearable v-model="strategyForm.couponId" filterable
                     :placeholder="$t('优惠券名称')">
            <el-option
              v-for="item in couponOptions"
              :label="item.name"
              :key="item.id"
              :value="item.id"
              @change="couponOption"
              :disabled="item.status===0||item.status===2">
              <span style="float: left">{{ item.name }}</span>
              <span v-if="item.status===0" style="float: right; color: #8492a6; font-size: 13px">{{ $t('未上架') }}</span>
              <span v-if="item.status===2" style="float: right; color: #8492a6; font-size: 13px">{{ $t('已使用') }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('使用范围')" prop="ranges">
          <el-checkbox-group v-model="strategyForm.ranges">
            <el-checkbox border :label="1" name="ranges">{{ $t('APP') }}</el-checkbox>
            <el-checkbox border :label="2" name="ranges">{{ $t('POS') }}</el-checkbox>
            <el-checkbox border :label="3" name="ranges">{{ $t('网站') }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item :label="$t('折扣类型')" prop="discountType">
          <el-radio-group v-model="strategyForm.discountType">
            <el-radio border :label="1">{{ $t('满减') }}</el-radio>
            <el-radio border :label="2">{{ $t('折扣') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="strategyForm.discountType==1" :label="$t('满减金额')" prop="discount">
          <el-input class="inputSty" :placeholder="$t('请输入内容')" v-model="strategyForm.discount">
            <template slot="append">{{ $t('Dollars') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="strategyForm.discountType==2" :label="$t('折扣')" prop="discountRate">
          <el-input class="inputSty" :placeholder="$t('请输入内容')" v-model="strategyForm.discountRate">
            <template slot="append">{{ $t('%') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('最低消费')" prop="min">
          <el-input class="inputSty" :placeholder="$t('请输入内容')" v-model="strategyForm.min">
            <template slot="append">{{ $t('Dollars') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="strategyForm.couponType==7||strategyForm.couponType==8" :label="$t('充值额度')" prop="rechargeAmount">
          <el-input class="inputSty" :placeholder="$t('请输入内容')" v-model="strategyForm.rechargeAmount">
            <template slot="append">{{ $t('Dollars') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="strategyForm.couponType==8" :label="$t('礼物卡')" prop="rechargeGift">
          <el-select
            multiple
            collapse-tags
            clearable
            v-model="strategyForm.rechargeGift"
            filterable
            :placeholder="$t('礼物卡')">
            <el-option
              v-for="item in gifts"
              :label="item.name"
              :key="item.id"
              :value="item.id"
              :disabled="item.status!=1">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="strategyForm.couponType==6" :label="$t('付费会员')" prop="payMember">
          <el-select
            v-model="strategyForm.payMember"
            multiple
            collapse-tags
            filterable
            placeholder="请选择等级会员">
            <el-option
              v-for="item in payMemberOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.status!=2">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="strategyForm.couponType==6||strategyForm.couponType==5" :label="$t('每次发放量')" prop="releasedQuantity">
          <el-input-number class="inputSty" :placeholder="$t('请输入内容')" :min="1" v-model="strategyForm.releasedQuantity">
            <template slot="append">{{ $t('张') }}</template>
          </el-input-number>
        </el-form-item>
        <el-form-item v-show="strategyForm.couponType==6" :label="$t('发放周期')" prop="period">
          <el-radio-group v-model="strategyForm.period">
            <el-radio-button :label="1">{{ $t('每天') }}</el-radio-button>
            <el-radio-button :label="2">{{ $t('每周') }}</el-radio-button>
            <el-radio-button :label="3">{{ $t('每月') }}</el-radio-button>
            <el-radio-button :label="4">{{ $t('每年') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-show="strategyForm.couponType==1" :label="$t('每人限领')"
                      prop="userLimit">
          <el-input class="inputSty" :placeholder="$t('请输入内容')" v-model="strategyForm.userLimit">
            <template slot="append">{{ $t('张') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="[1,7,8].includes(strategyForm.couponType)"
                      :label="$t('发放数量')" prop="total">
          <el-input class="inputSty" :placeholder="$t('请输入内容')" v-model="strategyForm.total">
            <template slot="append">{{ $t('量') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="[1,5,3].includes(strategyForm.couponType)" :label="$t('使用限制')"
                      prop="useLimit">
          <el-select clearable label-width="80px" v-model="strategyForm.useLimit" :placeholder="$t('请选择')">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          {{ $t('使用') }}
          <el-input v-if="strategyForm.useLimit != 4" style="width: 200px;" :placeholder="$t('请输入内容')"
                    v-model="strategyForm.useLimitNum">
            <template slot="append">{{ $t('张') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="strategyForm.couponType==1" :label="$t('优惠券区')" prop="isShow">
          <el-radio-group v-model="strategyForm.isShow">
            <el-radio border :label="true">{{ $t('展示') }}</el-radio>
            <el-radio border :label="false">{{ $t('隐藏') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('有效期')" prop="timeType">
          <el-radio-group v-model="strategyForm.timeType">
            <el-radio-button :label="1">{{ $t('时间范围') }}</el-radio-button>
            <el-radio-button :label="0">{{ $t('有效天数') }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="strategyForm.timeType==1" :lable="$t('开始日期')" prop="startTime">
          <el-date-picker v-model="strategyForm.startTime" type="datetime" :placeholder="$t('开始日期')"
                          value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item>
        <el-form-item v-show="strategyForm.timeType==1" :lable="$t('结束日期')" prop="endTime">
          <el-date-picker v-model="strategyForm.endTime" type="datetime" :placeholder="$t('结束日期')"
                          value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item>
        <el-form-item v-show="strategyForm.timeType==0" :label="$t('有效天数')" prop="days">
          <el-input :placeholder="$t('请输入天数')" v-model="strategyForm.days">
            <template slot="append">{{ $t('张') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="strategyForm.couponType==5" :label="$t('可使用等级')" prop="levelMember">
          <el-select
            v-model="strategyForm.levelMember"
            multiple
            collapse-tags
            style="margin-left: 20px;"
            placeholder="请选择等级">
            <el-option
              v-for="item in levelMemberOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="损耗承受单位" prop="lossBearing">
          <el-radio-group v-model="strategyForm.lossBearing">
            <el-radio border :label="0">{{ $t('总部') }}</el-radio>
            <el-radio border :label="1">{{ $t('门店') }}</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item :label="$t('商品限制范围')">
          <el-radio-group v-model="strategyForm.goodsType">
            <el-radio border :label="0">{{ $t('Usable_in_any_situation') }}</el-radio>
            <el-radio border :label="1">{{ $t('指定分类') }}</el-radio>
            <el-radio border :label="2">{{ $t('指定商品') }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-show="strategyForm.goodsType === 1" prop="goodsValue">
          <el-cascader :options="categories" :props="props" v-model="strategyForm.goodsValue" :show-all-levels="false"
                       collapse-tags clearable>
          </el-cascader>
        </el-form-item>

        <el-form-item v-show="strategyForm.goodsType === 2"  prop="detailedGoodsValue">
          <el-select v-model="strategyForm.selectGoods" filterable multiple :placeholder='$t("请选择")' collapse-tags style="width: 480px">
            <el-option v-for="item in goodsList" :key="item.key" :label="item.label" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('区域限制')">
          <el-radio-group v-model="strategyForm.areaLimit">
            <el-radio border :label="0">{{ $t('不限区域') }}</el-radio>
            <el-radio border :label="1">{{ $t('限制区域') }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-show="strategyForm.areaLimit == 0 ? false : true" prop="regions">
          <el-cascader :options="locations" :props="regionProps" v-model="strategyForm.regions" :show-all-levels="false"
                       collapse-tags clearable>
          </el-cascader>
        </el-form-item>




        <el-form-item label="使用说明" prop="useInstruction">
          <el-input class="inputSty" maxlength="1200" :autosize="{ minRows: 2}" show-word-limit type="textarea"
                    v-model="strategyForm.useInstruction"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button v-show="formButton==='submit'" type="primary" icon="el-icon-s-promotion"
                     @click="submitForm('strategyForm')">{{ $t('生成策略') }}
          </el-button>
          <el-button v-show="formButton==='edit'" type="primary" icon="el-icon-check" @click="editForm">
            {{ $t('提交编辑') }}
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetForm('strategyForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-dialog title="发放记录" :visible.sync="isGrantDialogShow" width="90%">
      <el-table :data="grantLogsList"  style="width: 100%">
        <el-table-column align="center" property="id" label="编号" width="200"></el-table-column>
        <el-table-column align="center" property="strategyName" label="发放时策略名称" width="150"></el-table-column>
        <el-table-column align="center" property="couponName" label="发放时优惠券名称" width="200"></el-table-column>
        <el-table-column align="center" property="createName" label="发放人员" width="150"></el-table-column>
        <el-table-column align="center" property="num" label="发放数量" width="150"></el-table-column>
        <el-table-column align="center" property="cause" label="发放原因" width="200">
          <template slot-scope="scope">
            <el-popover
              v-if="scope.row.cause&&scope.row.cause.length>40"
              placement="top-start"
              width="600"
              trigger="click"
              :content="scope.row.cause">
              <el-button slot="reference">
                {{ scope.row.cause.length > 10 ? scope.row.cause.substring(0, 10) + '...' : scope.row.cause }}
                <i class="el-icon-thumb"></i>
              </el-button>
            </el-popover>
            <span v-else>{{scope.row.cause}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" property="aim" label="发放类型" width="150">
          <template slot-scope="scope">
            <el-tag type="success">{{grantAimMap[scope.row.aim] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" property="aimName" label="发放目标[所有用户/指定用户/等级用户/会员用户]" width="220">
          <template slot-scope="scope">
            <el-popover
              v-if="scope.row.aimName&&scope.row.aimName.length>5"
              placement="top-start"
              trigger="click">
              <ul class="infinite-list" style="overflow:auto">
                <li v-for="item in scope.row.aimName" class="infinite-list-item"><el-tag>{{item}}</el-tag></li>
              </ul>
              <el-button slot="reference">
                More than 5 people<i class="el-icon-thumb"></i>
              </el-button>
            </el-popover>
            <el-tag v-else v-for="item in scope.row.aimName">{{item}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" property="addTime" label="发放时间" width="200">
          <template slot-scope="scope">
            <i class="el-icon-time">{{scope.row.addTime}}</i>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="grantLogsTotal >= 10" :total="grantLogsTotal" :page.sync="listGrantQuery.page" :limit.sync="listGrantQuery.limit"
                  @pagination="handleGrantLogs"/>
    </el-dialog>

    <el-dialog :visible.sync="isPeriodDialogShow" :title="$t('发放')">
      <el-form ref="extCouponForm" :rules="extRules" status-icon :model="extCouponForm" label-width="100px">
        <el-form-item :label="$t('发放对象')" prop="timeType">
          <el-radio-group type="vertical" v-model="extCouponForm.isAll" size="small">
            <el-row style="margin-bottom: 10px;">
              <el-radio :label="0" size="medium">
                {{ $t('所有会员') }}
              </el-radio>
            </el-row>
            <el-row>
              <el-radio :label="1" size="medium">
                {{ $t('指定会员:') }}
                <el-select multiple v-model="extCouponForm.userIds" :disabled="extCouponForm.isAll != 1" filterable remote
                           :remote-method="getUser">
                  <el-option v-for="item in userOptions" :key="item.id" :label="item.username" :value="item.id">
                  </el-option>
                </el-select>
              </el-radio>
            </el-row>
            <el-row>
              <el-radio :label="2" size="medium">
                <el-select multiple v-model="extCouponForm.levelMemberType" :disabled="extCouponForm.isAll != 2"
                           :placeholder='$t("请选择等级会员")'>
                  <el-option v-for="item in levelMemberOptions" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-radio>
            </el-row>
            <el-row>
              <el-radio :label="3" size="medium">
                <el-select multiple v-model="extCouponForm.payMemberType" :disabled="extCouponForm.isAll != 3"
                           :placeholder='$t("请选择付费会员")'>
                  <el-option v-for="item in payMemberOptions" :key="item.id" :label="item.name" :value="item.id"
                             :disabled="item.status!=2">
                  </el-option>
                </el-select>
              </el-radio>
            </el-row>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('发放数量')" prop="numbers">
          <el-input type="number" v-model="extCouponForm.numbers" min="1">
          </el-input>
        </el-form-item>

        <el-form-item :label="$t('发放原因')" prop="remarks">
          <el-input type="textarea" :autosize="{ minRows: 2}" v-model="extCouponForm.remarks">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isPeriodDialogShow = false">{{ $t('Cancel') }}</el-button>
        <el-button type="primary" @click="confirmCouponGrant">{{ $t('Confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="drawerTitleMap[couponStrategysDetails.couponType]"
      :visible.sync="isDetailsDialogShow"
      width="60%">
      <el-descriptions v-loading="isDetailsDialogLoading" direction="vertical" :column="5" border>
        <el-descriptions-item label="优惠券ID">{{ couponStrategysDetails.couponId }}</el-descriptions-item>
        <el-descriptions-item label="优惠券名称">{{ couponStrategysDetails.couponName }}</el-descriptions-item>
        <el-descriptions-item label="赠送策略名称" :span="2">{{ couponStrategysDetails.strategyName }}
        </el-descriptions-item>
        <el-descriptions-item label="最低消费">{{ couponStrategysDetails.min }}</el-descriptions-item>
        <el-descriptions-item label="折扣类型">
          <el-tag size="small">
            {{ couponStrategysDetails.discountType == 1 ? $t('满减') : $t('折扣') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优惠折扣">
          <el-tag v-if="couponStrategysDetails.discountType==1" size="small">
            {{ couponStrategysDetails.discount + $t('Dollars') }}
          </el-tag>
          <el-tag v-else size="small">
            {{ couponStrategysDetails.discountRate }}%
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="有效期">
          <el-tag v-if="couponStrategysDetails.timeType==0" size="small">{{
              couponStrategysDetails.days + $t('天')
            }}
          </el-tag>
          <el-tag v-else size="small">
            <i class="el-icon-date"></i>
            {{ couponStrategysDetails.startTime + '-' + couponStrategysDetails.endTime }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="每人限领">{{ couponStrategysDetails.userLimit }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">{{
            couponStrategysDetails.status ? $t('开启') : $t('关闭')
          }}
        </el-descriptions-item>
        <el-descriptions-item label="商品范围">Vancouver</el-descriptions-item>

        <el-descriptions-item label="发行数量">{{ couponStrategysDetails.couponType==1?couponStrategysDetails.total:$t('不限') }}</el-descriptions-item>
        <el-descriptions-item label="使用限制:年月周日">{{
            useLimitMap[couponStrategysDetails.useLimit]
          }}
        </el-descriptions-item>
        <el-descriptions-item label="使用限制数量">
          {{ couponStrategysDetails.useLimit == 4 ? $t('不限') : couponStrategysDetails.useLimitNum }}
        </el-descriptions-item>
        <el-descriptions-item label="领取数量">{{ couponStrategysDetails.receiveNum }}</el-descriptions-item>
        <el-descriptions-item label="说明">
          {{ couponStrategysDetails.useInstruction }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <el-dialog style="margin:auto;width: 800px;text-align: center" title="导出券码" :visible.sync="exportdrawerShow">
      <h4>导出优惠券码</h4>
      <p>
        <el-input-number v-show="switchLayout" v-model="exportNum" :min="1" :max="20000" label="数量"></el-input-number>
        <el-input v-show="switchLayout==false" style="width: 100px" v-model="exportNum" label="数量"></el-input>
      </p>
      <h6 class="strategyType">说明：一次最多可导出20000个优惠码，超过的部分请分多次导出</h6>
      <el-progress :percentage="progress" :status="showProgress?'success':''"></el-progress>
      <p>
        <el-button :icon="switchLayout?'el-icon-back':''" @click="exportdrawerShow = false">取 消</el-button>
        <el-button :icon="switchLayout?'el-icon-news':''" :disabled="exportBtu" type="primary"
                   @click.prevent="handleExportNum">确 定
        </el-button>
      </p>
    </el-dialog>

  </div>
</template>

<script>
import {
  couponStrategys,
  statusStrategys,
  editStrategys,
  saveStrategys,
  removeStrategys,
  levelMemberStrategys,
  payMemberStrategys,
  detailsStrategys,
  giftsList,
  recycleStrategys,
  recycle,
  recycleDelete,
  grantLogs,
  saveCodeStrategys,
  grantStrategyExten
} from '@/api/couponStrategy'
import {optionCoupon} from '@/api/coupon1'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination'
import strategyCoupon from "./strategyCoupon.vue";
import {userOption} from "../../api/user";
import {getToken} from "../../utils/auth";
import XLSX from 'xlsx';
import {v4 as uuidv4} from 'uuid';
import QRCode from 'qrcode';
import {listCategory} from "../../api/category";
import {listLocationRegion} from "../../api/region";
import {listpPutaway} from "../../api/goods";

export default {
  name: "allCoupon",
  components: {Pagination, BackToTop},
  data() {
    const drawerTitleMap = {
      1: this.$t('电子优惠券'),
      2: this.$t('实体优惠券'),
      3: this.$t('推广优惠券'),
      4: this.$t('生日福利券'),
      5: this.$t('等级会员券'),
      6: this.$t('付费会员券'),
      7: this.$t('余额充值券'),
      8: this.$t('礼物卡充值券')
    }
    const drawerIconMap = {
      1: 'el-icon-shopping-cart-full',
      2: 'el-icon-bank-card',
      3: 'el-icon-circle-plus-outline',
      4: 'el-icon-present',
      5: 'el-icon-finished',
      6: 'el-icon-money',
      7: 'el-icon-coin',
      8: 'el-icon-bank-card',
    }
    const lossBearingMap = {
      0: this.$t('总部'),
      1: this.$t('门店')
    }
    const discountTypeMap = {
      1: this.$t('满减'),
      2: this.$t('折扣')
    }
    const rangesMap = {
      1: this.$t('APP'),
      2: this.$t('POS'),
      3: this.$t('网站')
    }
    const useLimitMap = {
      0: this.$t('年'),
      1: this.$t('月'),
      2: this.$t('周'),
      3: this.$t('日'),
      4: this.$t('不限')
    }

    const grantAimMap={
      0: this.$t('所有会员'),
      1: this.$t('指定会员'),
      2: this.$t('等级会员'),
      3: this.$t('付费会员'),
    }

    const useHintMs = [
      this.$t('如果字符过长，长按Tag标签可以查看完整优惠券名、策略名称！'),
      this.$t('概览模式的所有内容与普通显示一致可以更简单的全面的查看、操作策略。'),
      this.$t('NO是该策略的唯一标识编号，序号是当前页的策略排序。'),
      this.$t('开启的策略请查看过期时间，如果设置的时间过期但仍然开启的话，APP并不会显示该券！'),
      this.$t('在实体券中导出券码时请不要轻易移开焦点，耐心等待导出完成。(可以关闭导出页面，后台仍会进行导出)'),
      this.$t('在创建策略时，需按照要求填写完所有数据后再提交，若是缺少部分信息策略可能不会生效！'),
    ]

    const couponSrcIconMap = {
      1: 'https://app.lumierecafe.com/mi/lumierecafe/app/coupon.png',
      2: 'https://app.lumierecafe.com/mi/lumierecafe/app/coupon.png',
      3: 'https://app.lumierecafe.com/mi/lumierecafe/app/coupon.png',
      4: 'https://app.lumierecafe.com/mi/lumierecafe/app/birthday.png',
      5: 'https://app.lumierecafe.com/mi/lumierecafe/app/level.png',
      6: 'https://app.lumierecafe.com/mi/lumierecafe/app/member.png',
      7: 'https://app.lumierecafe.com/mi/lumierecafe/app/balance.png',
      8: 'https://app.lumierecafe.com/mi/lumierecafe/app/gift.png',
    }
    //自定义表单校验规则
    const validateNum = (rule, value, callback) => {
      const reg = /^(?!0)\d+(\.\d+)?$/
      if (value === '') {
        callback(new Error('请输入数值'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确数值[只能输入正数且不能为0或者0开头]!'))
      } else {
        callback()
      }
    };
    //自定义表单校验规则
    const validateDouble = (rule, value, callback) => {
      const reg = /^(?!0(\.0+)?$)\d+(\.\d+)?$/
      if (value === '') {
        callback(new Error('请输入数值'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确数值[只能输入数字和小数且不能为0]!'))
      } else {
        callback()
      }
    };

    return {
      loading: true,
      //切换布局
      switchLayout: true,

      showProgress: false,
      exportBtu: false,
      progress: 0,
      //存储导出的券码
      exportCode: {
        strategyId: undefined,
        code: []
      },


      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        status: '',
        bearing: '',
        couponType: ''
      },
      options: [{
        value: 0,
        label: this.$t('每年')
      }, {
        value: 1,
        label: this.$t('每月')
      }, {
        value: 2,
        label: this.$t('每周')
      }, {
        value: 3,
        label: this.$t('每天')
      }, {
        value: 4,
        label: this.$t('不限')
      },
      ],
      useHintMs,
      formButton: '',
      strategyForm: {
        id: undefined,
        couponId: undefined,
        name: '',
        couponName: '',
        ranges: [],
        discountType: undefined,
        discount: 0,
        min: 0,
        userLimit: 0,
        rechargeAmount: 0,
        rechargeGift: [],
        total: 0,
        useLimit: undefined,
        useLimitNum: undefined,
        isShow: undefined,
        timeType: 1,
        startTime: undefined,
        endTime: undefined,
        days: undefined,
        lossBearing: undefined,
        useInstruction: undefined,
        status: undefined,
        levelMember: [],
        payMember: [],
        releasedQuantity: undefined,
        period: undefined,
        goodsType: 1,
        goodsValue: [],
        areaLimit: 0,
        regions: [],
        selectGoods: [],
      },
      categories: [],
      goodsList: [],
      locations: [],
      props: { multiple: true, value: 'id', label: 'name', emitPath: false },
      regionProps: { multiple: true, value: 'id', label: 'nameEn', emitPath: false },


      extCouponForm: {
        id: undefined,
        levelMemberType: [],
        payMemberType: [],
        numbers: undefined,
        remarks: undefined,
        isAll: 0,
        userIds: []
      },
      couponStrategysDetails: {},
      gifts: [],
      userOptions: [],
      payMemberOptions: [],
      levelMemberOptions: [],
      couponOptions: [],
      useLimitMap,
      couponSrcIconMap,
      rangesMap,
      discountTypeMap,
      drawerIconMap,
      lossBearingMap,
      drawerTitleMap,
      grantAimMap,
      drawerTitle: 1,
      drawer: false,
      exportdrawerShow: false,
      exportStrategys: undefined,
      exportNum: 1,
      isPeriodDialogShow: false,
      isGrantDialogShow: false,
      isDetailsDialogShow: false,
      isDetailsDialogLoading: false,
      //策略发放记录
      grantLogsList:[],
      grantLogsloading:false,
      grantLogsTotal: 0,
      listGrantQuery: {
        page: 1,
        limit: 20,
        id:undefined
      },
      value: true,
      currentDate: new Date(),
      //表单规则
      extRules: {
        numbers: [
          {required: true, validator: validateNum, trigger: 'blur'},
        ],
      },
      strategyRules: {
        name: [
          {required: true, message: '请输入策略名称', trigger: 'blur'},
          {min: 3, max: 255, message: '长度在 3 到 255 个字符', trigger: 'blur'}
        ],
        couponId: [
          {required: true, message: '请选择优惠券', trigger: 'change'}
        ],
        ranges: [
          {type: 'array', required: true, message: '请至少选择一个使用范围', trigger: 'change'}
        ],
        discountType: [
          {required: true, message: '请选择折扣类型', trigger: 'change'}
        ],
        lossBearing: [
          {required: true, message: '请选择损耗承受单位', trigger: 'change'}
        ],
        /*      discountRate: [
               { required: false, validator: validateDouble, trigger: 'blur' },
             ],
            total: [
                { required: false, validator: validateNum, trigger: 'blur' },
              ],
              discount: [
                { required: false, validator: validateNum, trigger: 'blur' },
              ],
              userLimit: [
                { required: false, validator: validateNum, trigger: 'blur' },
              ],
              min: [
                { required: false, validator: validateNum, trigger: 'blur' },
              ],
             rechargeAmount: [
               { required: false, validator: validateNum, trigger: 'blur' },
             ],*/

        /*days: [
          {required: false, validator: validateNum, trigger: 'blur'},
        ],
        isShow: [
          {required: false, message: '请选择是否展示在优惠券区', trigger: 'change'}
        ],
        timeType: [
          {required: false, message: '请选择有效期', trigger: 'change'}
        ],

        useLimit: [
          {required: false, message: '请选择使用限制', trigger: 'change'}
        ],
        levelMember: [
          {required: false, message: '请选择等级会员', trigger: 'change'}
        ],
        payMember: [
          {required: false, message: '请选择付费会员', trigger: 'change'}
        ],
        rechargeGift: [
          {required: false, message: '请选择礼物卡', trigger: 'change'}
        ],*/
      }
    }
  },
  created() {
    this.getList()

    this.getCategories()
    this.getLocations()
    this.getGoods()
  },
  methods: {
    confirmCouponGrant() {
      this.$refs['extCouponForm'].validate(valid => {
        if (valid) {
          //this.isPeriodDialogShow = false
          console.log(JSON.stringify(this.extCouponForm))
          grantStrategyExten(this.extCouponForm).then(res=>{
            this.$notify({
              title: '成功',
              message: '发放推广券发放成功',
              type: 'success'
            });
          }) .catch(() => {
            this.$message.error(this.$t('发放推广券发放失败'));
          })
        }
      })

    },
    getUser(keyword) {
      if (!keyword || keyword.length < 2) {
        return
      }
      this.listLoading = true
      userOption({keyword: keyword})
        .then(response => {
          this.userOptions = response.data.data
        })
        .catch(() => {
          this.userOptions = []
        })
    },
    couponOption(val) {
      this.$notify({
        title: '成功',
        message: val,
        type: 'success'
      });
    },
    resetForm(formName) {
      this.resetStrategyForm()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveStrategys(this.strategyForm).then(res => {
            this.$message({
              message: this.$t('成功创建策略-') + '[' + this.strategyForm.name + ']',
              type: 'success'
            });
            this.drawer=false
            this.resetStrategyForm()
          }).catch(() => {
            this.$message.error(this.$t('创建策略失败'));
            this.drawer=false
            this.getList()
          })
        } else {
          this.$message.error(this.$t('提交失败，请按照规则填写策略信息'));
          return false;
        }
      });
    },
    editForm() {
      editStrategys(this.strategyForm).then(res => {
        this.$message({
          message: this.$t('编辑成功-') + '[' + this.strategyForm.name + ']',
          type: 'success'
        });
        this.drawer = false
      }).catch(() => {
        this.$message.error(this.$t('编辑失败'));
        this.getList()
      })
    },
    strategyCoupon() {
      return strategyCoupon
    },
    getList() {
      couponStrategys(this.listQuery).then(res => {
        this.list = res.data.data.list
        this.total = res.data.data.total
        this.loading=false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.loading=false
      })

    },
    handleClose(done) {
      if (this.formButton === 'submit') {
        this.resetStrategyForm()
        done();
      } else {
        this.$confirm('改变的数据将不会保留，确认关闭？')
          .then(_ => {
            this.resetStrategyForm()
            this.getList()
            done();
          })
          .catch(_ => {
          });
      }
    },
    handleStatistic(item) {
      this.$router.push({path: '/coupon/strategyCouponStatistic', query: {id: item.id}})
    },

    handleGrantLogs(item){
      this.isGrantDialogShow=true
      this.listGrantQuery.id=item.id
      console.log(JSON.stringify(this.listGrantQuery))
      grantLogs(this.listGrantQuery).then(res => {
        this.grantLogsList = res.data.data.list
        this.grantLogsTotal = res.data.data.total
        this.grantLogsloading=false
      }).catch(() => {
        this.grantLogsList = []
        this.grantLogsTotal = 0
        this.grantLogsloading=false
      })
    },
    handleExport(item) {
      //初始化一些计算和存储的值
      this.exportCode.code = []
      this.exportCode.strategyId = undefined
      this.exportdrawerShow = true
      this.exportNum = 0
      this.progress = 0
      this.exportStrategys = item.id
      this.showProgress = false
    },

    async handleExportNum() {
      this.exportBtu = true
      this.showProgress = false
      this.progress = 0;
      const totalProgress = this.exportNum; // 总进度
      let currentProgress = 0; // 当前进度
      this.exportCode.strategyId = this.exportStrategys
      // 生成数据
      const data = [['UUID', 'QR Code']]
      for (let i = 0; i < this.exportNum; i++) {
        // 模拟异步加载数据
        await new Promise(resolve => setTimeout(resolve, 1));
        //const id = uuidv4() + '-' + Date.now()
        const id = this.generateId(6)+ Date.now()
        const qrCode = await QRCode.toDataURL(id)
        data.push([id, qrCode])

        this.exportCode.code.push(id);
        // 计算当前进度
        currentProgress++;
        this.progress = Math.floor((currentProgress / totalProgress) * 100);
      }
      this.showProgress = true;
      this.exportBtu = false;
      // 生成 Workbook 对象
      const workbook = XLSX.utils.book_new()
      const sheet = XLSX.utils.aoa_to_sheet(data)
      XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1')
      // 导出 Excel 文件
      XLSX.writeFile(workbook, 'couponCode.xlsx')
      this.saveStrategyCode(this.exportCode)
    },
    generateId(idLength) {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let id = '';
      for (let i = 0; i < idLength; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        id += characters.charAt(randomIndex);
      }
      return id;
    },

    //开始保存导出的券码到数据库
    async saveStrategyCode(item) {
      saveCodeStrategys(item).then(res=>{
        this.$message({
          message: '券码已经全部成功存储，已经可以使用了',
          type: 'success'
        });
      }).catch((res) => {
        if(res.data.errno==-1){
          this.$message({
            message: '券码存储失败，可能是中断了！',
            type: 'warning'
          });
        }
      })
    },
    handlePeriod(item) {
      this.isPeriodDialogShow = true
      //发放完成后清空发放表单
      this.extCouponForm = {
        id: undefined,
        levelMemberType: [],
        payMemberType: [],
        numbers: undefined,
        remarks: undefined,
        isAll: 0,
        userIds: []
      };
      this.extCouponForm.id = item.id
      levelMemberStrategys().then(res => {
        this.levelMemberOptions = res.data.data
      })
      payMemberStrategys().then(res => {
        this.payMemberOptions = res.data.data
      })
    },
    handleDetails(item) {
      this.isDetailsDialogShow = true
      this.isDetailsDialogLoading = true
      detailsStrategys({id: item.id}).then(res => {
        this.couponStrategysDetails = res.data.data
        this.isDetailsDialogLoading = false
      }).catch(() => {
        this.isDetailsDialogLoading = false
      })
    },
    handleRemove(item) {
      if (item.status == 1) {
        this.$message({
          message: this.$t('策略正在执行中，不可删除'),
          type: 'warning'
        });
        return;
      }
      removeStrategys({id: item.id}).then(res => {
        console.log(res)
        this.$message({
          message: this.$t('删除成功-') + '[' + item.name + ']',
          type: 'success'
        });
        this.drawer = false
        this.getList()
        return;
      }).catch((res) => {
        console.log(res)
        this.$message.error(this.$t('删除失败'));
      })
    },
    handleEdit(item) {
      this.formButton = 'edit'
      optionCoupon().then(res => {
        this.couponOptions = res.data.data
      }).catch(() => {
        this.couponOptions = []
      })
      this.strategyForm = item
      this.drawerTitle = item.couponType
      this.drawer = true
      //如果是等级会员策略 则加载等级会员
      if (item.couponType == 5) {
        levelMemberStrategys().then(res => {
          this.levelMemberOptions = res.data.data
        })
      }
      if (item.couponType == 6) {
        payMemberStrategys().then(res => {
          this.payMemberOptions = res.data.data
        })
      }
      if (item.couponType == 8) {
        giftsList().then(res => {
          this.gifts = res.data.data
        })
      }
    },
    handleCommand(command) {
      this.formButton = 'submit'
      this.drawerTitle = command
      this.strategyForm.couponType = command
      this.drawer = true
      optionCoupon().then(res => {
        this.couponOptions = res.data.data
      }).catch(() => {
        this.couponOptions = []
      })
      //如果是等级会员策略 则加载等级会员
      if (command == 5) {
        levelMemberStrategys().then(res => {
          this.levelMemberOptions = res.data.data
        })
      }
      if (command == 6) {
        payMemberStrategys().then(res => {
          this.payMemberOptions = res.data.data
        })
      }
      if (command == 8) {
        giftsList().then(res => {
          this.gifts = res.data.data
        })
      }
    },
    //手动清空表单
    resetStrategyForm() {
      this.strategyForm.id = undefined
      this.strategyForm.couponId = undefined
      this.strategyForm.name = ''
      this.strategyForm.couponName = ''
      this.strategyForm.ranges = []
      this.strategyForm.discountType = undefined
      this.strategyForm.discount = 0
      this.strategyForm.min = 0
      this.strategyForm.userLimit = 0
      this.strategyForm.total = 0
      this.strategyForm.useLimit = undefined
      this.strategyForm.useLimitNum = undefined
      this.strategyForm.isShow = undefined
      this.strategyForm.timeType = undefined
      this.strategyForm.startTime = undefined
      this.strategyForm.endTime = undefined
      this.strategyForm.days = undefined
      this.strategyForm.lossBearing = undefined
      this.strategyForm.useInstruction = undefined
      this.strategyForm.status = undefined
      this.strategyForm.levelMember = [],
        this.couponOptions = [],
        this.rechargeAmount = 0,
        this.rechargeGift = []
    },
    handleDijiPush(item) {
      item.status = item.status ? false : true
      statusStrategys(item).then(res => {
        this.$notify({
          message: '成功',
          type: 'success'
        });
      }).catch((res) => {
        if (res.data.errno == 401) {
          this.$notify.error({
            title: '错误',
            message: '开启失败,策略中的优惠券未上架！',
            type: 'error'
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '开启失败',
            type: 'error'
          });
        }
        item.status = false
      })
    },
    handlePush(item) {
      statusStrategys(item).then(res => {
        if (item.status) {
          this.$notify({
            title: '成功',
            message: '成功开启策略',
            type: 'success'
          });
        } else {
          this.$notify({
            title: '成功',
            message: '成功关闭策略',
            type: 'success'
          });
        }
      }).catch((res) => {
        if (res.data.errno == 401) {
          this.$notify.error({
            title: '错误',
            message: '开启失败,策略中的优惠券未上架！',
            type: 'error'
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '开启失败',
            type: 'error'
          });
        }
        item.status = false
      })
    },
    //地区限制
    getCategories() {
      listCategory().then(response => {
        this.categories = response.data.data.list
        if (this.dataForm.goodsValue && this.dataForm.goodsValue.length > 0) {
          let p = [];
          this.dataForm.goodsValue.forEach(goodsId => {
            this.categories.forEach(category => {
              if (category.children && category.children.length > 0) {
                category.children.forEach(item => {
                  if (item.children && item.children.length > 0) {
                    item.children.forEach(sub => {
                      if (sub.id == goodsId) {
                        let tmp = sub.id;
                        p.push(tmp)
                      }
                    })
                  }
                })
              }
            })
          })
          this.dataForm.goodsValue = p;
        }
      })
    },
    getLocations() {
      listLocationRegion().then(response => {
        this.locations = response.data.data.list
        if (this.dataForm.regions && this.dataForm.regions.length > 0) {
          let p = [];
          this.dataForm.regions.forEach(id => {
            this.locations.forEach(region => {
              if (region.children && region.children.length > 0) {
                region.children.forEach(item => {
                  if (item.children && item.children.length > 0) {
                    item.children.forEach(sub => {
                      if (sub.id == id) {
                        let tmp = sub.id;
                        p.push(tmp)
                      }
                    })
                  }
                })
              }
            })
          })
        }
      })

    },
    getGoods() {
      this.listLoading = true
      listpPutaway(this.listGoodsQuery).then(response => {
        this.goodsList = response.data.data.list.map(goods => {
          return {
            label: goods.name,
            key: goods.id
          }
        })
      }).catch(() => {
        this.list = []
      })
    },


  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  }
}
</script>

<style scoped>
.input-with-select {
  margin: 20px 30px 0px 0px;
  width: 300px;
  transition: all 0.3s;
}

.strategyType {
  font-size: 12px;
  color: #999
}

.time {
  font-size: 13px;
  color: #999;
}

.inputSty {
  width: 90%;
}

.cardTag {
  width: 140px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.image {
  width: 100%;
  height: 150px;
  display: block;
}

/*原图样式*/
.yuanSty {
  line-height: 25px;
  width: 80px;
  font-size: 14px;
}

.bottom {
}
</style>
